package edu.biwu.request;

import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;

import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.UUID;
import java.util.stream.Collectors;

@WebServlet("/req/upload02")
@MultipartConfig
public class RequestUploadDemo02 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Collection<Part> uploadFiles = request.getParts();
        for (Part uploadFile : uploadFiles) {
            String fileName = uploadFile.getSubmittedFileName();

            String extension = fileName.substring(fileName.lastIndexOf("."));
            String newFilename= UUID.randomUUID()+ extension;

            File file = new File("D:/uploadFile");
            if (!file.exists()) {
                file.mkdirs();
            }

            uploadFile.write(file+"/"+newFilename);
        }

        String fileNames = uploadFiles.stream().map(uploadFile -> uploadFile.getSubmittedFileName())
                .collect(Collectors.joining(","));

        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write(fileNames+"上传成功");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
